from django.shortcuts import render,HttpResponse,redirect,HttpResponsePermanentRedirect
from rest_framework.views import APIView
from rest_framework.response import Response
from captcha.image import ImageCaptcha
import jwt,redis,random,json,requests
import string,re,time
from zbj.my_redis import r
from zbj.models import *
from zbj.sms_code import sms_code
from zbj.my_jwt import jj
from zbj.urlis.tool import Get_resource
from qiniu import Auth
from zbj.urlis.tool import Get_It_type
# 导包密码加密
from django.contrib.auth.hashers import make_password,check_password
r_redis=redis.Redis(host='localhost', port=6379,db=1)
# 生成图片验证码的接口
class Img_code(APIView):
    def get(self,request):
        uuid=request.query_params.get("uuid")
        img_code="".join(random.sample(string.digits+string.ascii_letters,4))
        cap=ImageCaptcha()
        img=cap.generate(img_code)
        r.set_str(uuid,img_code,120)
        return HttpResponse(img,content_type="image/png")

# 生成短信验证码
class Sms_code(APIView):
    def post(self,request):
        uuid = request.data.get("uuid")
        imgcode=request.data.get("imgcode")
        mobile=request.data.get("mobile")
        if not all([uuid,mobile,imgcode]):
            return Response({"code":400,'msg':'字段不完整'})
        if not re.findall(r"1[3-9]\w{9}$",mobile):
            return Response({"code":400,'msg':'手机号格式错误'})
        mob=r.get_str("code"+mobile)
        if mob:
            return Response({"code":400,'msg':'请勿重复操作'})
        res=r.get_str(uuid)
        if res:
            res=res.decode()
            if res.lower()!=imgcode.lower():
                return Response({"code":400,'msg':'图片验证码错误'})
            sms_code(mobile)
            r.del_str(uuid)
            return Response({"code":200,'msg':'发送成功，请注意查收'})
        else:
            return Response({"code":400,'msg':'图片验证码过期，请刷新重试'})

# 手机号登录
class mobile_Login(APIView):
    def post(self,request):
        smscode=request.data.get("smscode")
        mobile=request.data.get("mobile")
        if not all([smscode,mobile]):
            return Response({"code":400,'msg':'请输入完整的信息进行登录'})
        res=r.get_str(mobile)   #短信验证码解码
        if res:
            res=res.decode()
            if res!=smscode:
                return Response({"code":400,'msg':'手机号验证码错误，请重新输入'})
            try:
                r.del_str(mobile)
                user=User.objects.get(mobile=mobile)
                print("user>>>>>>>",user)
                token=jj.jwt_encode(data={"data":{"id":user.id,"mobile":user.mobile}})
                role_list=Get_resource(int(user.role_id))
                return Response({"code":200,'msg':'登陆成功',"token":token,'userid':user.id,"role_list":role_list})
            except:
                return Response({"code":400,'msg':'未找到改手机号，请返回注册'})
        else:
            return Response({"code":400,'msg':'验证码已过期，请重新发送'})

# 注册
class mobile_register(APIView):
    def post(self,request):
        smscode=request.data.get("smscode")
        mobile=request.data.get("mobile")
        value=request.data.get("value")
        if not all([smscode,mobile,value]):
            return Response({"code":400,'msg':'请输入完整的信息进行登录'})
        res=r.get_str(mobile)   #短信验证码解码
        if res:
            res=res.decode()
            if res!=smscode:
                return Response({"code":400,'msg':'手机号验证码错误，请重新输入'})
            res=User.objects.all()
            for i in  res:
                if i.mobile==mobile:
                    return Response({"code":400,'msg':'用户名已存在'})
            try:
                User.objects.get(mobile=mobile)
                return Response({"code": 400, 'msg': '已查到您的手机号，请返回登录'})
            except:
                r.del_str(mobile)
                dada = time.time()
                dada = f"{str(dada)[3:7]}{str(dada)[-6:]}"
                user = User.objects.create(mobile=mobile, name=dada, role_id=int(value))
                token = jj.jwt_encode(data={"data":{"id": user.id, "mobile": user.mobile}})
                role_list = Get_resource(int(user.role_id))
                return Response(
                    {"code": 200, 'msg': f'注册成功，您的初始账号为{dada}', "token": token, 'userid': user.id,"role_list":role_list})
        else:
            return Response({"code":400,'msg':'验证码已过期，请重新发送'})

# 获取role
class Get_role(APIView):
    def get(self,request):
        ress = r.get_str("role")# 从redis中获取
        if ress:# 先判断redis里面有没有
            # 有了解码返回
            ress=ress.decode()
            return Response({"code": 200, 'msg':eval(ress)})
        # 没有从数据库查询
        res=Role.objects.all()
        # 序列化
        list=[]
        for i in res:
            list.append({
                "id":i.id,
                "name":i.name
            })
        r.set_str("role",str(list))
        return Response({"code":200,'msg':list})

# 第三方登录
# 1（拉起微博第三方接口）
class Wb_url(APIView):
    def get(self,request):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        return Response({"code":200,'url':url})

# 2 (从微博获取userid和token)
class Wb_token(APIView):
    def get(self,request):
        code=request.query_params.get("code")
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # 根据返回结果操作
        # 获取token和uid
        message=json.loads(res.text)
        token=message['access_token']
        uid=message['uid']
        # 查询数据库中是否存在，如果存在就用用户信息生成jwt  token返回
        try:
            res = Sf_login.objects.get(uid=uid)
            aid=res.userid_id
            res3=User.objects.get(id=int(aid)) # 根据用户id查询当前手机号
            print("查询到了，进行token生成")
            token=jj.jwt_encode(
                data={"data":{"id":res3.id,"mobile":res3.mobile}}
            )# jwt加密生成token
            print("走的有")
            role_list = Get_resource(int(res3.role_id))
            return HttpResponsePermanentRedirect("http://localhost:8080/sf_zhong?token="+token+"&userid="+str(res3.id)+"&role_list="+json.dumps(role_list))#跳转致中专页面
        except Exception as a:
            print("走的没有")
            return HttpResponsePermanentRedirect("http://localhost:8080/login1?token="+str(token)+"&uid="+str(uid))#跳转致中专页面

# 3 绑定
class add_sf_login(APIView):
    def post(self,request):
        uid=request.data.get("uid")
        mobile=request.data.get("mobile")
        token=request.data.get("token")
        role_id=request.data.get("roleid")
        if not all([uid,mobile,token]):
            return Response({"code":400,'msg':'字段不完整'})
        if not re.findall(r"1[3-9]\w{9}$", mobile):
            return Response({"code": 400, 'msg': '手机号格式错误'})
        try:
            res=User.objects.get(mobile=mobile)
            Sf_login.objects.create(uid=uid,sf_token=token,sf_type="wb",userid_id=res.id)
            token = jj.jwt_encode(
                data={"data": {"id": res.id, "mobile": res.mobile}}
            )  # jwt加密生成token
            role_list = Get_resource(int(res.role_id))
            return Response({"code":200,'token':token,'userid':res.id,"role_list":role_list})
        except Exception as a:
            dada=time.time()
            dada = f"{str(dada)[3:7]}{str(dada)[-6:]}"
            User.objects.create(mobile=mobile,role_id=int(role_id),name=dada)
            res=User.objects.get(mobile=mobile)
            Sf_login.objects.create(uid=uid, sf_token=token, sf_type="wb", userid_id=res.id)
            role_list = Get_resource(int(res.role_id))
            token = jj.jwt_encode(
                data={"data": {"id": res.id, "mobile": res.mobile}}
            )  # jwt加密生成token
            return Response({"code":200,'token':token,'userid':res.id,"role_list":role_list})

# 需要对用户进行实名注册
class Autonym(APIView):
    def get(self,request):
        uid=request.data.get("c")
        print("uid>>>>>>>>",uid)
        token = request.headers.get('token')
        print("213123123")
        if not all([token]):
            url="http://localhost:8080/home/"
            return Response({"code":401,"url":url})
        else:
            user =jj.jwt_decode(token)
            user=dict(user)
            user=user['data']
            userid=user['id']
            try:
                identity.objects.get(userid_id=userid)
                url="http://localhost:8080/demand/"
                return Response({"code":200,"url":url})
            except Exception as a:
                return Response({"code":402,"url":"http://localhost:8080/autonym/"})

# 七牛云获取token
class imgqny(APIView):
    def get(self,request):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'VWKXpfhRZSeT-SMMo4HEJ708LO6pd4rBBToTQv36'
        secret_key = 'CpX7R__itUIcFNH-JQ2uop1Wu-syEoAQvlkhp0SR'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'adminctg1'
        # 上传后保存的文件名
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name)
        return Response({"code":200,'token':token})

# 获取文字识别接口
from zbj.urlis.baidu import bd

class character(APIView):
    def post(self,request):
        "http://rpuhgscze.hb-bkt.clouddn.com/1.jpg"
        data = request.data.get("imgurl")
        # 调取接口进行传参
        res = bd.getmes(data)
        # 给获取到的数据内容赋值
        res0=res[0]['words']
        res1 = res[1]['words']
        # 切片取出前17位
        res3=res0[0:17]
        print(type(res0))
        print(type(res1))
        try:
            # 判断里面是否是数字
            int(res3)
            # 如果是数字就进行赋值，第一个是身份证号码，第二个是用户姓名
            res0 = res[1]['words']
            res1 = res[0]['words']
            return Response({"code": 200, 'msg': res0, 'msg2': res1})
            # 如果不是数字就把赋值内容颠倒，第2个是身份证号码，第1个则是用户姓名
        except:
            res1 = res[1]['words']
            res0 = res[0]['words']
            return Response({"code":200,'msg':res0,'msg2':res1})

# 进行用户绑定接口
class user_identity(APIView):
    def post(self,request):
        name=request.data.get("name")
        code=request.data.get("code")
        s_type=request.data.get("s_type")
        userid=request.data.get("userid")
        if not all([name,code,s_type,userid]):
            return Response({"code":400,'msg':'字段不完整'})
        try:
            identity.objects.get(userid_id=userid)
            return Response({"code":400,'msg':'已检测到您曾实名认证，请勿重复认证'})
        except Exception as a:
            identity.objects.create(name=name,code=code,itype=s_type,userid_id=userid)
            return Response({"code":200,'msg':'恭喜您认证成功！！！'})

# 获取所有类型
class Get_Itype(APIView):
    def get(self,request):
        pid=None
        list=Get_It_type(pid)
        return Response({"code":200,'msg':list})

# 银行卡绑定
class Y_code(APIView):
    def get(self,request):
        userid=request.query_params.get("userid")
        if not all([userid]):
            return Response({"code":400,'msg':'字段不完整'})
        try:
            list=[]
            res=Bank.objects.filter(userid=userid)
            for i in res:
                list.append({
                    "id":i.id,
                    "sf_yh":i.sf_yh,
                    "bank_card":i.bank_card
                })
            return Response({"code":200,'list':list})
        except Exception as a:
            return Response({"code":400,'url':"http://localhost:8080/top_up"})
    def post(self,request):
        y_type=request.data.get("y_type")
        y_code=request.data.get("y_code")
        userid=request.data.get("userid")
        if not all([y_type,y_code,userid]):
            return Response({"code":400,'msg':'字段不完整'})
        try:
            Bank.objects.get(sf_yh=y_type,bank_card=y_code,userid_id=userid)
            return Response({"code":400,'msg':'该卡已被绑定，请勿重复操作'})
        except Exception as a:
            Bank.objects.create(sf_yh=y_type,bank_card=y_code,userid_id=userid)
            return Response({"code":200,'msg':'绑卡成功'})

# 支付接口
from zbj.urlis.comm import get_ali_object
class ailpay_jie(APIView):
    def get(self,request):
        pay=get_ali_object()
        id="1"
        name="11111111111111"
        res=f"{id}_{name}_{random.randint(10000,99999)}"
        print("res>>>>>>>>",res)
        query_params=pay.direct_pay(
            subject="坑你钱的", # 商品描述
            out_trade_no=str(res),# 用户购买的商品订单号，每次不一样
            total_amount=float(100.100),
            name=name,
            id=id
        )
        pay_url="https://openapi.alipaydev.com/gateway.do?{0}".format(query_params) # 支付宝网关地址
        return Response({"code":200,'msg':pay_url})
    def post(self,request):
        bank_card=request.data.get("bank_card")
        userid=request.data.get("userid")
        money=request.data.get("money")
        if not all([bank_card,userid,money]):
            return Response({"code":400,'msg':'字段不完整'})
        res=Bank.objects.get(bank_card=bank_card)
        if res.money<money:
            return Response({"code":400,'msg':'银行卡余额不足'})
        try:
            money=float(money)
            red = random.randint(10000000000000000, 99999999999999999)
            pay=get_ali_object()
            query_params=pay.direct_pay(
             subject="猪八戒网平台充值",
             out_trade_no=str(red),
             total_amount=money
            )
            recharge_record.objects.create(
                dd_code=str(red),
                yhk_code=bank_card,
                money=float(money),
                userid=userid,
                mtime=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
            )
            pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址
            return Response({"code":200,'msg':pay_url})
        except:
            return Response({"code":400,'msg':'系统故障，请联系管理员'})

# 支付宝回调地址
import datetime
class callback(APIView):
    def get(self,request):
        data=request.query_params
        print(">>>>>",data)
        data = {k: v for k, v in data.items()}
        # 从字典中把sign删除
        sign = data.pop("sign")
        print('去掉签名的data>>>>>>>>>>>>>>>>>>',data)
        # 获取支付宝对象
        alipay = get_ali_object()
        # 调用验签
        flag = alipay.verify(data,sign)
        print(flag)
        if flag == True:
            try:
                # 鉴权成功
                trade_no=data['trade_no']
                ddcode=data['out_trade_no']
                res=recharge_record.objects.get(dd_code=ddcode)
                code=res.yhk_code
                id=res.userid
                meny=res.money
                print(f"银行卡号为{code}，用户id为{id}，金额为{meny}")
                # 查询当前银行卡余额，并进行修改
                res=Bank.objects.get(bank_card=code,userid_id=id)
                money=float(res.money)-float(meny)
                Bank.objects.filter(bank_card=code,userid_id=id).update(money=float(money))
                #=================================================================
                # 查询到用户的余额
                res2=User.objects.get(id=id)
                money=float(res2.property)+float(meny)
                User.objects.filter(id=id).update(property=money)
                #=================================================================
                # 写入金额记录表
                Amount_record.objects.create(
                    price=meny,
                    ptime=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'),
                    user_id_id=id,
                    describe="猪八戒平台账户充值"
                )
                # 对充值订单表进行一个修改状态
                recharge_record.objects.filter(dd_code=ddcode).update(
                    state="已完成",
                    trade_no=trade_no
                )
                return Response({"code": 200, 'msg': 'ok'})
            except Exception as a:
                return Response({"code":400,'msg':'支付出现错误，请联系管理员'})
        else:
            return Response({"code":400,'msg':'鉴权失败'})
#   进行需求发布
#   调用雪花算法
from zbj.urlis.tool import create_ordercode


class Add_demand(APIView):
    def post(self,request):
        tablename,code=create_ordercode("Demand",3)
        project_name=request.data.get("project_name")
        typelei=request.data.get("typelei")
        describe=request.data.get("describe")
        img=request.data.get("img")
        price=request.data.get("price")
        userid=request.data.get("userid")
        type_id=request.data.get("type_id")
        charge_mode=request.data.get("charge_mode")
        mobile=request.data.get("mobile")
        ask_fro=request.data.get("ask_fro")
        if not all([tablename,project_name,typelei,describe,img,price,userid,type_id,charge_mode,mobile,ask_fro]):
            return Response({"code":400,'msg':'字段不完整'})
        userid=int(userid)
        # 查询出来当前用户
        res=User.objects.get(id=userid)
        # 判断当前用户除去锁定金额后还剩多少钱
        yue=float(res.property)-float(res.no_property)
        print(price,">>>>>>>>>>>>",yue)
        # 判断当前用户可用余额是否大于发布项目所需金额
        if float(price)>float(yue): # 如果项目所需金额大于可用金额
            return Response({"code":400,'msg':'余额不足，请进行充值'}) # 返回余额不足
        print("分表进行中>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        print(f"分表内容>>>表名是{tablename},code是{code}")
        tablename = globals().get(f"{tablename}")
        print("分表完成>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        tablename.objects.create(
            code=code,
            project_name=project_name,
            typelei=typelei,
            describe=describe,
            img=img,
            price=float(price),
            userid_id=userid,
            type_id_id=type_id,
            charge_mode=charge_mode,
            mobile=mobile,
            ask_fro=ask_fro,
            state=1,
            ttm=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
        )
        # 查询到响应角色的所属内容
        res1=User.objects.get(id=userid)
        # 获取到当前角色的锁定金额
        money1=res1.no_property
        # 将当前锁定金额与项目金额相加
        money1=float(money1)+float(price)
        User.objects.filter(id=userid).update(
            no_property=money1
        )
        r.list_push("code",code)
        return Response({"code":200,'msg':'添加成功'})

# 获取数据（外包）
from zbj.urlis.tool import get_Demand_type,get_Demand
class Get_Demand(APIView):
    def get(self,request):
        page=request.query_params.get("page")
        typeid=request.query_params.get("typeid")
        if typeid=="aaa":
            list=get_Demand(page)
            return Response({"code":200,'msg':list})
        else:
            list = get_Demand_type(page,typeid)
            return Response({"code": 200, 'msg': list})

# 获取详情
class GetDemand_x(APIView):
    def get(self,request):
        code=request.query_params.get("code")
        if code==None:
            return Response({"code":400,'msg':"缺少数据"})
        print("code>>>",code)
        number = hash(int(code)) % 3
        print("取余>>>>>",number)
        if number==0:
            tablename="Demand"
            table0 = globals().get(tablename)
            res=table0.objects.get(code=code)
            list=[]
            list.append({
                    "code":res.code,
                    "project_name":res.project_name,
                    "typelei":res.typelei,
                    "describe":res.describe,
                    "img":res.img,
                    "price":res.price,
                    "charge_mode":res.charge_mode,
                    "mobile":res.mobile,
                    "ask_fro":res.ask_fro,
                    "state":res.state,
                    "ttm":res.ttm.strftime("%Y-%m-%d %H:%M:%S"),
                    "user":res.userid.name,
                    "userid": res.userid_id,
                    "type":res.type_id.type_name
            })
            return Response({"code":200,'msg':list})
        else:
            tablename = "Demand"
            tablename=f"{tablename}{number}"
            table0 = globals().get(tablename)
            res = table0.objects.get(code=code)
            list = []
            list.append({
                "code": res.code,
                "project_name": res.project_name,
                "typelei": res.typelei,
                "describe": res.describe,
                "img": res.img,
                "price": res.price,
                "charge_mode": res.charge_mode,
                "mobile": res.mobile,
                "ask_fro": res.ask_fro,
                "state": res.state,
                "ttm": res.ttm.strftime("%Y-%m-%d %H:%M:%S"),
                "user":res.userid.name,
                "userid": res.userid_id,
                "type": res.type_id.type_name})
            return Response({"code": 200, 'msg': list})

# 导入哈希取模
from zbj.urlis.tool import Hashdelivery

# 接单
class order_receiving(APIView):
    def post(self,request):
        key="fenbu"
        flag=r_redis.setnx(key+"setnx",1)
        if flag==True:
            try:
                userid=request.data.get("userid")
                code=request.data.get("code")
                uid=request.data.get('uid')
                if not all([userid,code,uid]):
                    r_redis.delete(key + "setnx")
                    return Response({"code":400,'msg':'字段不完整'})
                # 判断接单
                pdjd=Receipt_record.objects.filter(code=code).count()
                print("pdjd>>>>>>>>>>>>>>>>>>",pdjd)
                if pdjd!=0:
                    return Response({"code":400,'msg':"该项目已被接手"})
                res=User.objects.get(id=userid)
                if res.role_id!=2:
                    r_redis.delete(key + "setnx")
                    return Response({"code":200,'msg':'您没有卖服务的权限'})
                # （服务商）接单记录表
                Receipt_record.objects.create(
                    code=code,
                    join_time=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'),
                    user_id_id=userid,
                    state=1,
                    fuser_id=uid
                )
                # （雇主）外包表里面的状态
                number=Hashdelivery(code)
                if number==0:
                    tablename="Demand"
                    table0 = globals().get(tablename)
                    table0.objects.filter(code=code).update(
                        state="2"
                    )
                    r_redis.delete(key + "setnx")
                    return Response({"code": 200, 'msg': '成功'})
                else:
                    tablename = "Demand"
                    tablename=f'{tablename}{number}'
                    table0 = globals().get(tablename)
                    table0.objects.filter(code=code).update(
                        state="2"
                    )
                    r_redis.delete(key + "setnx")
                    return Response({"code":200,'msg':'成功'})
            except Exception as a:
                return Response({"code":400,'msg':'失败，请联系管理员'})
        r_redis.delete(key+"setnx")

# 雇主查看是否完成
class Get_receipt_record(APIView):
    # 查看被接单的项目
    def get(self,request):
        userid=request.query_params.get("userid")
        list=[]
        if not userid:
            return Response({"code":400,'msg':'请返回登录'})
        res=User.objects.get(id=userid)
        roleid=res.role_id
        print("roleid>>>>",roleid)
        if roleid==1:
            # 雇主看的是项目流程
            res2=Receipt_record.objects.filter(fuser_id=userid)
            for i in res2:
                list.append({
                    "id":i.id,
                    "code":i.code,
                    "join_time":i.join_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "user_id":i.user_id.id,
                    "state":i.state,
                    "fuser_id":i.fuser_id
                })
            return Response({"code":200,'msg':list})
        else:
            # 服务商看的是项目
            res2 = Receipt_record.objects.filter(user_id_id=userid)
            for i in res2:
                list.append({
                    "id":i.id,
                    "code":i.code,
                    "join_time":i.join_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "user_id":i.user_id.id,
                    "state":i.state,
                    "fuser_id":i.fuser_id
                })
            return Response({"code": 200, 'msg': list})
    # 查看已完成的项目
    def post(self,request):
        userid = request.data.get("userid")
        list = []
        if not userid:
            return Response({"code": 400, 'msg': '请返回登录'})
        res = User.objects.get(id=userid)
        roleid = res.role_id
        print("roleid>>>>", roleid)
        if roleid == 1:
            # 雇主看的是项目流程
            res2 = Receipt_record.objects.filter(fuser_id=userid,state=2)
            for i in res2:
                list.append({
                    "id": i.id,
                    "code": i.code,
                    "join_time": i.join_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "user_id": i.user_id.id,
                    "state": i.state,
                    "fuser_id": i.fuser_id
                })
            return Response({"code": 200, 'msg': list})
        else:
            # 服务商看的是项目
            res2 = Receipt_record.objects.filter(user_id_id=userid,state=2)
            for i in res2:
                list.append({
                    "id": i.id,
                    "code": i.code,
                    "join_time": i.join_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "user_id": i.user_id.id,
                    "state": i.state,
                    "fuser_id": i.fuser_id
                })
            return Response({"code": 200, 'msg': list})

# 清算（结算，项目结业，撒花*”*“*”*“*”）
class clearing(APIView):
    def post(self,request):
        userid = request.data.get("userid")
        code=request.data.get("code")
        if not all([userid,code]):
            return Response({"code":400,'msg':'内容不完整'})
        # 查询当前用户userid所属的角色
        res = User.objects.get(id=userid)
        roleid = res.role_id
        print("roleid>>>>", roleid)
        pricelist=[]
        if roleid == 1:
        # 加事务
        # 雇主是结清金额
            try:
               user2 = Receipt_record.objects.get(code=code)
               if user2.state!=2:
                   return Response({"code":400,'msg':'项目状态不匹配，我知道你很急，但你先别急'})
               number=Hashdelivery(code)
               if number==0:
                   tablename="Demand"
                   tablename = globals().get(tablename)
                   res1=tablename.objects.get(code=code)
                   pricelist.append(res1.price)
               else:
                   tablename =f"Demand{number}"
                   tablename = globals().get(tablename)
                   res1 = tablename.objects.get(code=code)
                   pricelist.append(res1.price)
               price=pricelist[0]
               print("price>>>>",price)
               # User表减去锁定金额
               userprice=res.property
               not_price=res.no_property
               userprice=userprice-price
               # User表减去项目金额
               not_price=not_price-price
               print(f"减去的金额为{userprice},锁定金额为{not_price}")
               User.objects.filter(id=userid).update(property=userprice,no_property=not_price)
               # User表服务商加项目金额
               user2=Receipt_record.objects.get(code=code)
               user3=User.objects.get(id=user2.user_id_id)
               jine=user3.property+price
               User.objects.filter(id=user2.user_id_id).update(property=jine)
               print("修改成功")
               # 写入金额记录表（支付项目）
               jinji=f"-{price}"
               jinji=float(jinji)
               print(jinji)
               print(type(jinji))
               Amount_record.objects.create(
                   price=jinji,
                   ptime=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'),
                   user_id_id=userid,
                   describe="支付项目金额"
               )
               Amount_record.objects.create(
                   price=price,
                   ptime=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S'),
                   user_id_id=user2.user_id_id,
                   describe=f"完成编号为：{code}项目所得金额",
               )
               Receipt_record.objects.filter(code=code).update(state=3)
               return Response({"code": 200, 'msg':"交易成功，已扣除需求金额"})
            except Exception as a:
               return Response({"code":400,'msg':"出事儿了，服务嗝屁了，喊管理员吧"})
        else:
            # 服务商完结项目
            Receipt_record.objects.filter(code=code).update(state=2)
            return Response({"code": 200, 'msg':"项目完成，已修改项目状态"})


